package cc.vv.baselibrary.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import cc.vv.baselibrary.bean.base.BaseResponseObj;
import cc.vv.baselibrary.global.BCSharePreKey;
import cc.vv.baselibrary.http.BaseHttpResponseKey;
import cc.vv.baselibrary.http.BaseHttpResponseObj;
import cc.vv.baselibrary.util.LKLogUtil;
import cc.vv.baselibrary.util.LKPrefUtil;
import cc.vv.baselibrary.util.router.RouterActivityIntentResourceKey;
import cc.vv.baselibrary.util.router.RouterTransferCenterUtil;
import cc.vv.baselibrary.vFinal.BTCodeKey;
import cc.vv.baselibrary.view.BCSingleButtonDialog;
import cc.vv.lklibrary.log.LogOperate;

/**
 * Created by 025 on 2018/7/12.
 */

public class UtimingBaseFragment extends BaseVisibilityFragment {

    private BCSingleButtonDialog dialog;

//    private BoTuBaseFragmentReceiver boTuBaseFragmentReceiver;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        try {
            EventBus.getDefault().register(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initView(Bundle bundle) {

    }


    @Override
    protected void initData(@Nullable Bundle bundle) {
        super.initData(bundle);
    }


    @Override
    protected void initAction(@Nullable Bundle bundle) {
        super.initAction(bundle);
    }


    @Override
    public void onResume() {
        super.onResume();

//        try {
//            if (null == boTuBaseFragmentReceiver) {
//                boTuBaseFragmentReceiver = new BoTuBaseFragmentReceiver();
//            }
//            //实例化IntentFilter对象
//            IntentFilter filter = new IntentFilter();
//            filter.addAction(BaseHttpResponseKey.FRAGMENT_REQUEST_BROADCAST_KEY);
//            //注册广播接收
//            getActivity().registerReceiver(boTuBaseFragmentReceiver, filter);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    @Override
    public void onStop() {
        super.onStop();
//        try {
//            //解注册
//            if (null != boTuBaseFragmentReceiver) {
//                getActivity().unregisterReceiver(boTuBaseFragmentReceiver);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

    }

    @Override
    public void onPause() {
        super.onPause();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
            dialog = null;
        }
        try {
            //解注册
            EventBus.getDefault().removeAllStickyEvents();
            EventBus.getDefault().unregister(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 100)
    public void onEvent(BaseHttpResponseObj event) {
        setRequestResultData(event);
    }


    /**
     * 请求结果数据设置
     */
    private void setRequestResultData(BaseHttpResponseObj event) {
        if (null == event) {
            return;
        }
        if (!isVisible()) {
            return;
        }
        if (BaseHttpResponseKey.RESPONSE_TYPE_START.equals(event.getResponseType())) {
            //请求开始
            if (event.isLoading()) {
                getLoading().showLoading();
            }
        } else if (BaseHttpResponseKey.RESPONSE_TYPE_SUCCESS.equals(event.getResponseType())) {
            //请求成功success
            BaseResponseObj data = event.getData();
            if (null != data) {
                if (data.statusCode == BTCodeKey.CODE_200) {
                    getData(data);
                } else if ("A".equals(data.level)) {
                    getData(data);
                } else {
                    if (data.statusCode == BTCodeKey.CODE_10002) {
                        //token失效
//                        showDistanceLoginDialog();
                    } else {
                        getBadCode(data);
                    }
                }
            }

        } else if (BaseHttpResponseKey.RESPONSE_TYPE_FINISH.equals(event.getResponseType())) {
            //请求完成
            getLoading().closeLoading();
        } else if (BaseHttpResponseKey.RESPONSE_TYPE_FAILURE.equals(event.getResponseType())) {
            //请求失败
            onHttpFailure(event.getUrl(), event.getExceptionStr());
        }
    }


    /**
     * 接口请求成功code值为非200和300时
     */
    protected void getBadCode(BaseResponseObj obj) {

    }

    /**
     * 接口请求成功回调
     */
    protected void getData(BaseResponseObj obj) {

    }

    /**
     * 接口请求失败回调
     */
    protected void onHttpFailure(String url, String exceptionStr) {
        LKLogUtil.e(url + ":" + exceptionStr);
    }

    private void showDistanceLoginDialog() {
        if (null == dialog) {
            try {
                dialog = new BCSingleButtonDialog(getActivity());
                dialog.setTitle("下线通知");
                dialog.setContent("你的账号在另一台设备登录，如非本人操作，则密码可能已泄露，请你修改密码。");
                dialog.setConfirmBtnText("重新登录");
                dialog.setEventInterface(new BCSingleButtonDialog.EventInterface() {
                    @Override
                    public void confirmOnClick() {
                        //跳转登录
                        dialog.dismiss();
                        LKPrefUtil.clearSP(BCSharePreKey.USERINFO_DATA);
                        Intent intent = RouterTransferCenterUtil.getInstance().getRouterIntent(getActivity(),
                                RouterActivityIntentResourceKey.KEY_MODULE_LOGIN);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        startActivity(intent);
                    }
                });
            } catch (Exception e) {
                LogOperate.e(e.getMessage(), e);
            }
        }
        if (null != dialog && !dialog.isShowing()) {
            dialog.show();
        }
    }

//    class BoTuBaseFragmentReceiver extends BroadcastReceiver {
//
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            try {
//                if (null != intent && null != intent.getAction()) {
//                    if (intent.getAction().equals(BaseHttpResponseKey.FRAGMENT_REQUEST_BROADCAST_KEY)) {
//                        BaseHttpResponseObj obj = null;
//                        try {
//                            obj = (BaseHttpResponseObj) intent.getSerializableExtra(BaseHttpResponseKey.REQUEST_RESULT_KEY);
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                        if (null != obj) {
//                            setRequestResultData(obj);
//                        }
//                    }
//                    Log.e("BaseFragmentReceiver", "--------------");
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//
//    }

}
